import Login from "@/views/Login.vue";
import Register from "@/views/Register.vue";
import Home from "@/views/Home.vue";
import Index from "@/views/Index.vue";
import Share from "@/views/Share.vue";
import UserInfo from "@/views/UserInfo.vue";
import {createRouter, createWebHashHistory} from "vue-router";
import {getRequest} from "@/util/api";
import {flushLocalStorage} from "@/util/util";

const routes = [
    {
        path: '/',
        redirect: "/login",
    },
    {
        path: '/login',
        component: Login,
    },
    {
        path: '/register',
        component: Register,
    },
    {
        path: '/home',
        component: Home,
        redirect: '/index',
        children: [
            {
                path: '/index',
                component: Index,
            },
            {
                path: '/share',
                component: Share,
            },
            {
                path: '/userInfo',
                component: UserInfo,
            },
        ]
    },
];

const router = createRouter({
    history: createWebHashHistory(),
    routes
});

router.beforeEach(async (to, from, next) => {
    if (to.path === "/login") {
        if (localStorage.getItem("token")) {
            await getRequest("/user/verifyToken", null, (res) => {
                localStorage.setItem("token", res.data.data);
                next("/home");
            }, () => {
                flushLocalStorage();
                next("/login");
            });
        } else {
            next();
        }
    } else if (to.path === "/register") {
        next();
    } else if (localStorage.getItem("token")) {
        await getRequest("/user/verifyToken", null, (res) => {
            localStorage.setItem("token", res.data.data);
            next();
        }, () => {
            flushLocalStorage();
            next("/login");
        });
    } else {
        next("/login");
    }
});

export default router;
